import { useState, useMemo } from 'react';
import ImportModal from '@/components/work/Checklist/ImportFlow/ImportModal';
import type { ImportItem } from '@/components/work/Checklist/ImportFlow/types';
import type { FiltersType, ComplianceItem, MaturityLevelStat } from '@/types/work';
import { ProgressStatus } from '@/types/work';
import { 
  ComplianceHeader, 
  ComplianceFilters, 
  ComplianceList
} from '@/components/work';
import { useComplianceStore } from '@/stores/useComplianceStore';
import { exportComplianceItemsToExcel, sortComplianceItems } from '@/utils/utils';
import { showMessage } from '@/components/common/MessageTip';
import { useBusiness } from '@/stores/useBusinessStore';
import workApi from '@/api/work';
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal';
import { getAssessmentTypeName } from '@/utils/utils';

/**
 * 检查项视图组件
 */
const ComplianceView = () => {
  // 从 store 中获取状态和操作方法
  const { 
    items, 
    updateItem, 
    deleteItem,
  } = useComplianceStore();
  

  const { selectedBusiness } = useBusiness();
  
  // 本地过滤器状态
  const [filters, setFilters] = useState<FiltersType>({
    compliance_type: 'all',
    riskLevel: 'all',
    progressStatus: 'all',
    complianceStatus: 'all',
    searchTerm: '',
    maturityLevel: 'all'
  });
  
  // 计算过滤后的项目
  const filteredItems = useMemo(() => {
    return sortComplianceItems(items.filter(item => {
      // 按类型过滤
      if (filters.compliance_type !== 'all' && item.compliance_type !== filters.compliance_type) return false;
      
      // 按风险等级过滤
      if (filters.riskLevel !== 'all' && item.risk_level !== filters.riskLevel) return false;
      
      // 按进度状态过滤
      if (filters.progressStatus !== 'all' && item.progress_status !== filters.progressStatus) return false;

      // 按保障状态过滤
      if (filters.complianceStatus !== 'all' && item.compliance_status !== filters.complianceStatus) return false;

      // 按成熟度等级过滤（数据安全评估）
      if (filters.maturityLevel !== 'all' && item.maturity_level?.toString() !== filters.maturityLevel) return false;

      // 按标题关键字过滤（忽略大小写）
      if (filters.searchTerm.trim() && !item.title.toLowerCase().includes(filters.searchTerm.toLowerCase())) return false;
      return true;
    }));
  }, [items, filters.compliance_type, filters.riskLevel, filters.progressStatus, filters.complianceStatus, filters.searchTerm, filters.maturityLevel]);
  
  // 重置过滤器
  const resetFilters = () => {
    setFilters({
      compliance_type: 'all',
      riskLevel: 'all',
      progressStatus: 'all',
      complianceStatus: 'all',
      searchTerm: '',
      maturityLevel: 'all'
    });
  };
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(5);
  // 下拉菜单状态
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  // 导出确认对话框状态
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);

  // 计算完成进度
  const calculateProgress = () => {
    const completedItems = items.filter(item => item.progress_status === ProgressStatus.COMPLETED);
    return items.length > 0 ? Math.round((completedItems.length / items.length) * 100) : 0;
  };

  // 计算成熟度等级统计（仅数据安全评估）
  const maturityLevelStats = useMemo((): MaturityLevelStat[] => {
    const isDataSecurityAssessment = selectedBusiness?.assessmentType === '105';
    
    if (!isDataSecurityAssessment || items.length === 0) {
      return []
    }
    
    // 获取所有存在的成熟度等级
    const levels = Array.from(new Set(
      items
        .map(item => item.maturity_level)
        .filter((level): level is number => level !== undefined && level !== null)
    )).sort((a, b) => a - b)
    
    // 统计每个等级的完成情况
    return levels.map(level => {
      const levelItems = items.filter(item => item.maturity_level === level)
      const completedLevelItems = levelItems.filter(item => item.progress_status === ProgressStatus.COMPLETED)
      const progressPercent = levelItems.length > 0 
        ? Math.round((completedLevelItems.length / levelItems.length) * 100)
        : 0
      
      return {
        level,
        total: levelItems.length,
        completed: completedLevelItems.length,
        progress: progressPercent
      }
    })
  }, [items, selectedBusiness?.assessmentType]);
  
  // 分页处理
  const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredItems.slice(indexOfFirstItem, indexOfLastItem);
  
  // 处理过滤器变更
  const handleFilterChange = (newFilters: Partial<FiltersType>) => {
    setFilters(prev => ({
      ...prev,
      ...newFilters
    }));
    setCurrentPage(1);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };
  
  const handleItemsPerPageChange = (count: number) => {
    setItemsPerPage(count);
    setCurrentPage(1);
    setIsDropdownOpen(false);
  };

  // 快速跳转到最近的进行中(IN_PROGRESS)项所在页
  const jumpToInProgress = () => {
    // 禁用条件：当状态筛选不为全部时提示并返回
    if (filters.progressStatus !== 'all') {
      showMessage('warning', '请先将状态筛选设为“全部”，再使用“待完成”定位');
      return;
    }
    // 基于当前其他筛选条件(类型/风险/关键词)，但忽略进度状态，计算基础列表
    const baseFiltered = sortComplianceItems(items.filter(item => {
      if (filters.compliance_type !== 'all' && item.compliance_type !== filters.compliance_type) return false;
      if (filters.riskLevel !== 'all' && item.risk_level !== filters.riskLevel) return false;
      if (filters.searchTerm.trim() && !item.title.toLowerCase().includes(filters.searchTerm.toLowerCase())) return false;
      return true;
    }));
    // 寻找最近的进行中项
    const targetIndex = baseFiltered.findIndex(i => i.progress_status === ProgressStatus.IN_PROGRESS);
    if (targetIndex === -1) {
      showMessage('info', '没有进行中的检查项');
      return;
    }
    const page = Math.floor(targetIndex / itemsPerPage) + 1;
    setCurrentPage(page);
    showMessage('info', `已跳转到最近的进行中的检查项`);
  };

  const handleToggleDropdown = () => {
    setIsDropdownOpen(!isDropdownOpen);
  };

  const handleUpdateItem = async (item: Partial<ComplianceItem> & { id: string }) => {
    try {
      await updateItem(item.id, item);
      showMessage('success', '检查项更新成功');
    } catch (error) {
      console.error('更新失败:', error);
      showMessage('error', '检查项更新失败');
    }
  };
  
  const handleDeleteItem = async (id: string) => {
    try {
      await deleteItem(id);
      showMessage('success', '检查项删除成功');
    } catch (error) {
      console.error('删除失败:', error);
      showMessage('error', '检查项删除失败');
    }
  };

  // 导出检查材料 - 显示确认对话框
  const handleExportMaterial = () => {
    if (!selectedBusiness?.id) {
      showMessage('error', '请先选择业务系统');
      return;
    }
    setIsDropdownOpen(false);
    setIsExportModalOpen(true);
  };

  // 确认导出 - 实际下载操作
  const handleConfirmExport = async () => {
    try {
      setIsExportModalOpen(false);
      
      // 调用导出API
      const blob = await workApi.exportAssessmentPlanAttachments(selectedBusiness!.id);
      
      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${selectedBusiness!.name}_${getAssessmentTypeName(selectedBusiness!.assessmentType || '101')}_附件.zip`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      
      // 清理URL对象
      setTimeout(() => URL.revokeObjectURL(url), 1000);
      
      showMessage('success', '检查材料导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      // 使用统一错误处理后的 error.message
      showMessage('error', error.message || '检查材料导出失败');    }
  };

  // 导出检查项表格
  // 处理批量导入
  const handleImport = async (importItems: ImportItem[]) => {
    try {
      // 批量更新检查项
      await Promise.all(
        importItems.map(item => 
          updateItem(item.id, { inspector: item.inspector, 
            risk_level: item.risk_level, 
            compliance_status: item.compliance_status,
            compliance_type: item.compliance_type })
        )
      );
      showMessage('success', '批量导入成功');
    } catch (error) {
      console.error('导入失败:', error);
      showMessage('error', '批量导入失败');
    }
  };

  const handleExport = async () => {
    try {
      await exportComplianceItemsToExcel(items, `${selectedBusiness?.name}_${getAssessmentTypeName(selectedBusiness?.assessmentType ? selectedBusiness?.assessmentType : '101')}.xlsx`, selectedBusiness?.assessmentType ? selectedBusiness?.assessmentType : '101');
      setIsDropdownOpen(false);
      showMessage('success', '检查项表格导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      showMessage('error', '检查项表格导出失败');
    }
  };

  return (
    <>
      <ComplianceHeader 
        progress={calculateProgress()} 
        totalItems={items.length}
        completedItems={items.filter(item => item.progress_status === ProgressStatus.COMPLETED).length}
        maturityLevelStats={maturityLevelStats}
      />
      
      <div className="mt-4">
        <div className="flex flex-col sm:flex-row justify-between items-center gap-2 mb-2">
          <ComplianceFilters 
            filters={filters}
            setFilters={handleFilterChange}
            // 待完成：点击后在父组件判断并提示
            onJumpToInProgress={jumpToInProgress}
          />
          <div className="flex items-center space-x-2 min-h-[40px]">
            {/* 操作下拉菜单 */}
            <div className="relative">
              <button
                onClick={handleToggleDropdown}
                className="px-3 py-1.5 bg-primary text-primary-foreground rounded-md active:translate-y-[1px] transition-transform text-sm flex items-center"
              >
                操作
                <svg 
                  className={`ml-1 h-4 w-4 transition-transform ${isDropdownOpen ? 'rotate-180' : ''}`} 
                  fill="none" 
                  stroke="currentColor" 
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </button>
              {isDropdownOpen && (
                <div className="absolute z-10 mt-1 w-36 bg-popover rounded-md shadow-lg">
                  <div className="py-1">
                    <button
                      onClick={() => setIsImportModalOpen(true)}
                      className="w-full px-4 py-2 text-sm text-left active:translate-y-[1px] transition-transform"
                    >
                      批量导入
                    </button>
                    <button
                      onClick={handleExportMaterial}
                      className="w-full px-4 py-2 text-sm text-left active:translate-y-[1px] transition-transform"
                    >
                      导出检查材料
                    </button>
                    <button
                      onClick={handleExport}
                      className="w-full px-4 py-2 text-sm text-left active:translate-y-[1px] transition-transform"
                    >
                      导出检查项表格
                    </button>
                  </div>
                </div>
              )}
            </div>
            {/* 重置筛选按钮 */}
            <button
              onClick={() => {
                resetFilters();
                setCurrentPage(1);
              }}
              className="px-3 py-1.5 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 transition-colors text-sm"
            >
              重置筛选条件
            </button>
          </div>
        </div>
      </div>
      
      <div className="mt-4 bg-card rounded-lg shadow-sm p-4">
        <ComplianceList 
          items={currentItems} 
          updateItem={handleUpdateItem} 
          deleteItem={handleDeleteItem} 
        />
        
        {filteredItems.length > 0 && (
          <div className="mt-6 flex items-center justify-between text-sm text-muted-foreground">
            <div>
              显示 {indexOfFirstItem + 1}-{Math.min(indexOfLastItem, filteredItems.length)} 条，共 {filteredItems.length} 条
            </div>
            <div className="flex items-center space-x-2">
              <span>每页显示：</span>
              <div className="relative inline-block">
                <button
                  onClick={handleToggleDropdown}
                  className="inline-flex items-center justify-between w-20 px-3 py-1.5 text-sm border rounded-md hover:bg-accent focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
                >
                  {itemsPerPage}
                  <svg
                    className={`w-4 h-4 ml-1 transition-transform ${isDropdownOpen ? 'transform rotate-180' : ''}`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M19 9l-7 7-7-7"
                    />
                  </svg>
                </button>
                {isDropdownOpen && (
                  <div className="absolute right-0 z-10 w-20 mt-1 bg-white rounded-md shadow-lg">
                    {[5, 10, 20, 50].map((count) => (
                      <button
                        key={count}
                        onClick={() => handleItemsPerPageChange(count)}
                        className="block w-full px-4 py-2 text-sm text-left hover:bg-accent"
                      >
                        {count}
                      </button>
                    ))}
                  </div>
                )}
              </div>
              <div className="flex items-center space-x-1">
                <button
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="p-1 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-accent"
                >
                  <svg
                    className="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M15 19l-7-7 7-7"
                    />
                  </svg>
                </button>
                <span>
                  第 {currentPage} 页，共 {totalPages} 页
                </span>
                <button
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className="p-1 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-accent"
                >
                  下一页
                </button>
                
                <button
                  onClick={() => handlePageChange(totalPages)}
                  disabled={currentPage === totalPages || totalPages === 0}
                  className="px-2 py-1 rounded-md border border-input bg-background text-foreground hover:bg-accent disabled:opacity-50 disabled:pointer-events-none"
                >
                  尾页
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
      
      {/* 导出确认对话框 */}
      <DeleteConfirmModal
        isOpen={isExportModalOpen}
        onClose={() => setIsExportModalOpen(false)}
        onConfirm={handleConfirmExport}
        title="谨慎保存"
        itemName="检查材料附件"
        message="您确定要导出检查材料吗？"
        cancelText="取消"
        confirmText="确认导出"
        dangerMessage="下载材料中含有敏感信息，请谨慎保管"
      />
      {/* 导入模态框 */}
      <ImportModal
        isOpen={isImportModalOpen}
        onClose={() => setIsImportModalOpen(false)}
        onImport={handleImport}
        items={items}
      />
    </>
  );
};

export default ComplianceView; 